import {toJS} from "mobx"
import {Table,Icon,Row,Col,Button,Modal,InputNumber,message} from 'antd'
import {WeaInput,WeaSelect,WeaBrowser,WeaDialog,WeaNewScroll,WeaLocaleProvider,WeaError} from 'ecCom'
import './index.less'
import equal from "deep-equal"
import PrjDateTime from '../prj-data-time'
import {datediff} from '../../../util'
import AddProjectDialog from '../../dialog/addProjectDialog'
import {AddProjectStore} from "../../../stores/addProjectStore"
const getLabel = WeaLocaleProvider.getLabel;

class PrjTaskListTable extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			showModal:false,
			clickKey:"",
			datas:props.datas || [],
			selectedRowKeys: [],
			taskViewAttr :props.taskViewAttr||"",
		}
		this.remind1 = new Array();
		this.remind2 = new Array();
		this.remind3 = new Array();
	}
	componentDidMount() {
		const { datas = [], taskViewAttr} = this.props;
		const newdatas = this.addKeytoDatas(datas);
		this.setState({datas: this.changeBeforeTask(newdatas),taskViewAttr: taskViewAttr})
	}
	componentShouldUpdate(nextProps,nextState){
		return !equal(this.state,nextState)||!equal(this.props.nextProps)
	}
	componentWillReceiveProps(nextProps,nextState) {
		const {  datas = [], selectedRowKeys = [],taskViewAttr } = this.state;
		const _datas = nextProps.datas || [];
		const _selectedRowKeys = nextProps.selectedRowKeys || [];
		const _taskViewAttr = nextProps.taskViewAttr || "";
		!equal(datas,_datas) && this.setState({datas: this.addKeytoDatas(_datas)});
		!equal(taskViewAttr,_taskViewAttr) && this.setState({taskViewAttr: _taskViewAttr});
		!equal(selectedRowKeys,_selectedRowKeys) && this.setState({selectedRowKeys:_selectedRowKeys})
	}
	componentWillUnmount(){

    }
	addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i+1;
			_data.rowIndex = i+1;
			return _data
		})
		return _datas
	}
	 //change 前置任务
	 changeBeforeTask=(datas)=>{
        let _datas = [].concat(datas);
        _datas.map(item=>{
            if(item.beftaskid && item.beftaskid !== "0"){
                for(let i = 0 ;i < _datas.length; i++){
                    if(_datas[i].realid == item.beftaskid){
                        item.beftaskid = _datas[i].rowIndex;  
                        item.beftaskname = _datas[i].name;               
                    }
                }
            }
        })
        return _datas;
    }
	render() {
		const { datas,showModal,taskViewAttr } = this.state;
		return(
			<div className="wea-prj-table-edit" >
				<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@sx63mp`} className="wea-content" >
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@cda1ng`}  span={24}>
						<Table ecId={`${this && this.props && this.props.ecId || ''}_Table@d7n4g1`} 
							columns={this.getColumns()}
							dataSource={datas}
							pagination={false}
							rowSelection={this.getRowSelection()}
						/>
					 </Col>
                </Row>
				<WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@5oqo02`}
					style={{width: 700,height:450}}
					visible={showModal}
					title={getLabel(2233,"前置任务")}
					icon="icon-coms-project"
					iconBgcolor="#217346"
					buttons={this.getButtons()}
					onCancel={() => this.setState({showModal:false})}

				>  
					<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@2yn1pq`}  scrollId='wea-prj-table-edit-scroll' height={"100%"}>
						<div className="wea-prj-table-edit">
							<Table ecId={`${this && this.props && this.props.ecId || ''}_Table@f2menu`} 
								columns={this.getModalColumns()}
								dataSource={datas}
								pagination={false}
								onRowClick={this.onRowClick}
							/>
						</div>
					</WeaNewScroll>
				</WeaDialog> 
            </div>
		)
	}
	getColumns(){
		const {taskViewAttr } = this.state;
		const { stageOptions, isTimeShow } = this.props;
		let dis = true;
		if(taskViewAttr==2){
			dis = false;
		}
		return [{
            title: getLabel(15486,"序号"),
			dataIndex: 'rowIndex',
			width:"5%",
            render: (text, record, index ) => {return <span>{text}</span>},
          }, {
            title: getLabel(1352,"任务名称"),
			dataIndex: 'name',
			width:"20%",
			render: (text, record, index ) => <span>
				<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@qsxsqs`}
                    ref={(ref) => {
						this.remind1.push(ref);
					}}
                    error={getLabel(385869,"此项必填")}
                    tipPosition="top"
                    >
				<WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@3x0rh7`} 
					value={text} 
					viewAttr={3}
					style={{display: 'inline-block'}}
					onChange={value => this.onEdit(record, index,"name" , value)}
				/> 
				</WeaError>
			</span>,
          }, {
            title: getLabel('24902','阶段') ,
			dataIndex: 'stageid',
			width:"10%",
			render: (text, record, index ) => {
				return <span>
				<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@06fs56`}
                    ref={(ref) => {
						this.remind2.push(ref);
					}}
                    error={getLabel(385869,"此项必填")}
                    tipPosition="top"
                    >
				 <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@bwp8cv`}
                    options={stageOptions}
                    value={record.stageid == -1 ? "" : record.stageid}
                    viewAttr={3}
					onChange={value => this.onEdit(record, index,"stageid" , value)}
					style={{width:80}}
                />
				</WeaError>
				</span>},
          }, {
            title: getLabel(1298,"工期"),
			dataIndex: 'workday',
			width:"5%",
			render:(text, record, index)=><span>
				<InputNumber ecId={`${this && this.props && this.props.ecId || ''}_InputNumber@ia2kye`}  disabled={dis} value={text}  min={0} max={999999} precision={2}  step={0.01} />
			</span>
          }, {
            title: getLabel(742,"开始时间"),
			dataIndex: 'begindate',
			width:"15%",
			render:(text, record, index)=><span>
				<PrjDateTime ecId={`${this && this.props && this.props.ecId || ''}_PrjDateTime@kzu9r4`} {...{ 
					"viewAttr": taskViewAttr,
					"value":[text,record.begintime || "00:00"],
					"otherParams":{
						"noInput":true
					},
					"isTimeShow":isTimeShow
				}}
				endValue ={ new Date(record["enddate"])}
				onChange={(v)=>{this.timeComputed(v,"begin",index)}} />
			</span>
          }, {
            title: getLabel(743,"结束时间"),
			dataIndex: 'enddate',
			width:"15%",
			render:(text, record, index)=><span>
				<PrjDateTime ecId={`${this && this.props && this.props.ecId || ''}_PrjDateTime@25ibhr`} {...{ 
					"viewAttr": taskViewAttr,
					"value": [text,record.endtime || "23:59"],
					"otherParams":{
						"noInput":true
					},
					"isTimeShow":isTimeShow
				}}
				startValue ={ new Date(record["begindate"])} 
				onChange={(v)=>{this.timeComputed(v,"end",index)}} />
			</span>
          }, {
            title: getLabel(2233,"前置任务"),
			dataIndex: 'beftaskid',
			width:"15%",
			render:(text, record, index)=><span style={{whiteSpace:"nowrap"}}>
				<span>
					<WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@pfxwfo`} 
						viewAttr={1}
						hasBorder={true}
						value={record.beftaskname} 
					/>
				</span>
				{!dis&&<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@h20ka6`} type="search" className="icon-selebeforetask" style={{marginBottom:8}} onClick={()=>this.setState({showModal:true,clickKey:record.key})}/>}
			</span>
          },{
            title: getLabel(2097,"负责人"),
			dataIndex: 'hrmid',
			width:"20%",
			render:(text, record, index)=><span>
				<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@v4ox9q`}
                    ref={(ref) => {
						this.remind3.push(ref);
					}}
                    error={getLabel(385869,"此项必填")}
					tipPosition="top"
					style={{width:90}}
                    >
				<WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@fbsld9`}  
					viewAttr={3}
					type={17}
                    isSingle={false}
					onChange={(ids, names, bDatas) =>{this.onEdit( record, index,"hrmid",ids, names, bDatas)}}
					replaceDatas={[{id: text, name: record.hrmname}]}
				/>
				</WeaError>
			</span>
          }];
	}

	onEdit= (record, index,name , value,names,bDatas) =>{
		let that = this;
		const {clickKey,datas} = this.state;
		let _datas = [].concat(datas);
		if(name == "hrmid"){
			_datas[index][name]  = value ;
			_datas[index]["hrmname"]  = names ;
		}else{
			_datas[index][name]  = value ;
		}
		this.setState({datas : _datas});
		this.onChange(_datas);
	}

	getButtons(){
		let btn = [];
		btn.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@v9lfoi@clear`}  type="primary" onClick={()=>this.onClear()}>{getLabel(311,"清除")}</Button>);
		btn.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zb9ozk@close`}  type="primary" onClick={()=>this.setState({showModal:false,clickKey:""})}>{getLabel(309,"关闭")}</Button>);
		return btn;
	}
	getModalColumns(){
		return [{
            title: getLabel(15486,"序号"),
			dataIndex: 'rowIndex',
			width:"15%",
            render: (text, record, index ) =><span style={{marginLeft:5}}>{text}</span>,
          }, {
            title: getLabel(1352,"任务名称"),
			dataIndex: 'name',
			width:"85%",
			render: (text, record, index ) => <span>{text}</span>,
          }]
	}
	onRowClick=(record, index)=>{
		let that = this;
		const {clickKey,datas} = this.state;
		let _datas = [].concat(datas);
		if(record.key == clickKey){	
			// Modal.warning({
            //     title: getLabel(15172,"系统提示"),
			// 	content: getLabel(24468,"不能把本身设置为前置任务!"),
			// 	onOk() {
			// 		that.setState({showModal:false,clickKey:""})
			// 	  }
			// })
			message.error(getLabel(24468,"不能把本身设置为前置任务!"));
			that.setState({showModal:false,clickKey:""});
		}else{
			_datas[clickKey-1].beftaskname = record.name;
			_datas[clickKey-1].beftaskid = record.rowIndex;
			that.setState({showModal:false,clickKey:"",datas :_datas})
			this.onChange(_datas);
		}
	}

	onClear=()=>{
		let that = this;
		const {clickKey,datas} = this.state;
		let _datas = [].concat(datas);
		_datas[clickKey-1].beftaskname = "";
		_datas[clickKey-1].beftaskid = "";
		that.setState({showModal:false,clickKey:"",datas :_datas})
		this.onChange(_datas);
	}

	//计算工期
	timeComputed= (arg,type,index) =>{
		const {userid ,isworkday} = this.props;
		const {datas} = this.state;
		let _datas = [].concat(datas);
        let res = "";
        if(type == "begin"){
			let time = "";
			if(!arg[1]){time  =  "00:00" }else{time = arg[1]}
			if( _datas[index]["enddate"] && arg[0] ){
				res =  datediff(arg[0],_datas[index]["enddate"],time,_datas[index]["endtime"] || "23:59",userid,isworkday);
			}
			_datas[index]["begindate"] = arg[0]
			_datas[index]["begintime"] = time;
        }else{
			let time = "";
			if(!arg[1]){time  =  "00:00"}else{time = arg[1]}
			if(_datas[index]['begindate'] && arg[0] ){
				res =  datediff(_datas[index]['begindate'],arg[0],_datas[index]['begintime'] || "00:00",time,userid,isworkday);
			}
			_datas[index]["enddate"] = arg[0]
			_datas[index]["endtime"] = time;
		}
		_datas[index].workday = res;
        this.setState({datas:_datas})
		this.onChange(_datas);
	}
	
	getRowSelection(){
		let that = this;
		const rowSelection = {
			onChange(selectedRowKeys, selectedRows) {
				typeof that.props.onRowSelect === 'function' && that.props.onRowSelect(selectedRowKeys);
			},
			selectedRowKeys:that.props.selectedRowKeys
		}
		return rowSelection
	}

	onChange(datas){
		typeof this.props.onChange === 'function' && this.props.onChange(datas);
	}

	showErrors() {
		toJS(this.remind1).map(c => {
			if (c && !c.props.children.props.value && c.props.children.props.viewAttr == "3") {
				c.showError();
			}
		});
		toJS(this.remind2).map(c => {
			if (c && !c.props.children.props.value && c.props.children.props.viewAttr == "3") {
				c.showError();
			}
		});
		toJS(this.remind3).map(c => {
			if(c&&c.props.children.props.replaceDatas&&(c.props.children.props.replaceDatas[0]?!c.props.children.props.replaceDatas[0].id:!c.props.children.props.replaceDatas[0])&&c.props.children.props.viewAttr=="3"){
				c.showError();
			}
		});
	}
}

export default PrjTaskListTable;
